import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler, RobustScaler

def normalize_indicators(df, method='robust', cv_threshold=1.0):
    """
    对指标数据进行归一化处理，并返回每个指标采用的归一化方法。

    参数：
        df: 原始DataFrame，包括元数据与指标列。
        method: 归一化方法，'minmax' | 'robust' | 'dynamic'。
        cv_threshold: 动态归一化中用于判断的变异系数阈值。

    返回：
        df_scaled: 归一化后的DataFrame
        method_dict: 每个指标采用的归一化方法（仅在 dynamic 模式下返回）
    """
    meta_cols = ['序号', '国名En', '国名Ch', '年份']
    indicator_cols = [col for col in df.columns if col not in meta_cols]

    df_scaled = df.copy()
    method_dict = {}

    if method in ['minmax', 'robust']:
        scaler = MinMaxScaler() if method == 'minmax' else RobustScaler()
        scaled_data = scaler.fit_transform(df[indicator_cols])
        df_scaled = pd.concat([df[meta_cols].reset_index(drop=True),
                               pd.DataFrame(scaled_data, columns=indicator_cols)], axis=1)
        method_dict = {col: method for col in indicator_cols}

    elif method == 'dynamic':
        for col in indicator_cols:
            series = df[col]
            if series.mean() == 0:
                cv = 0
            else:
                cv = series.std() / series.mean()

            if cv > cv_threshold:
                transformed = np.log1p(series)
                scaler = MinMaxScaler()
                method_used = 'log+minmax'
            elif cv > 0.5:
                transformed = series
                scaler = RobustScaler()
                method_used = 'robust'
            else:
                transformed = series
                scaler = MinMaxScaler()
                method_used = 'minmax'

            df_scaled[col] = scaler.fit_transform(transformed.values.reshape(-1, 1))
            method_dict[col] = method_used

    else:
        raise ValueError("method must be 'minmax', 'robust' or 'dynamic'")

    return df_scaled, method_dict
